<?php

if (!defined('TOBBIVM'))
	header('location:/template/notrepassing.php');
/**
 * This file is part of TobbiVMShop.
 *
 * TobbiVMShop is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * TobbiVMShop is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with TobbiVMShop.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * Authenticate data from Login
 *
 * @version    $Id$
 * @package    TobbiVM-Shop
 * @copyright  Copyright (C) 2012
 * @author     Norbert Gebert
 * @license    GPL3
 */

/**
 * Verify User-Input from Login-Form
 *
 * @param  string $user     Username
 * @param  string $password Userpassword
 * @return mixed  returns true if Login ok
 */
function loginUser($user, $password, $cart, $refValidate)
{ 
	$user = $refValidate->cleanslash($user);
	$password = $refValidate->cleanslash($password);
	
	$cols = array('customer_secureid');
	db::getInstance()->where('customer_name', $user);
	db::getInstance()->where('customer_active', 1);
	$result = db::getInstance()->getOne('customer', NULL, $cols);


	if (db::getInstance()->count >= 1)
	{
		// If a record is found, the username exists,
		// so we check if the credentials are correct
		// Login password to prepare
		$secureid = $result['customer_secureid'];
		$userpw = md5($password . $secureid);

		$cols = array('customer_id', 'customer_errors', 'customer_level');
		db::getInstance()->where('customer_name', $user);
		db::getInstance()->where('customer_password', $userpw);
		db::getInstance()->where('customer_active', 1);
		$result = db::getInstance()->getOne('customer', NULL, $cols);

		if (db::getInstance()->count >= 1)
		{ // Checking if a record was found. In the case of voting credentials
			// Reset counter for failed attempts
			$_SESSION['levelx'] = $result['customer_level'];

			if ($result['customer_errors'] >= 1)
			{
				// Update the database
				$data = Array('customer_errors' => 0);
				db::getInstance()->where('customer_name', $user);
				db::getInstance()->update('customer', $data);
			}

			$cart->setCustomer($user);
			// return login ok
			return true;
		}
		else
		{ 
			// If the given password was incorrect, so we go from a trial
			// error and increase the counter of failed logon attempts
			$cols = array('customer_errors');
			db::getInstance()->where('customer_name', $user);
			db::getInstance()->where('customer_active', 1);
			$result = db::getInstance()->getOne('customer', NULL, $cols);

			// Update the database
			$data = Array('customer_errors' => ($result['customer_errors'] + 1));
			db::getInstance()->where('customer_name', $user);
			db::getInstance()->update('customer', $data);

			// if the limit has been reached of CUSTOMER_MAX_ATTEMPTS failed attempts, in this case ...
			// ...deactivate the user
			if (($result['customer_errors'] + 1) >= CUSTOMER_MAX_ATTEMPTS)
			{
				// Update the database
				$data = Array('customer_active' => 0);
				db::getInstance()->where('customer_name', $user);
				db::getInstance()->update('customer', $data);
			}
		}
	}
}

/**
 * Update Userdata
 *
 * @param  string $user     Username
 * @return mixed  returns true if the update ok
 */
function updateUser($user)
{
	// Update the database
	$data = Array(
	 'customer_ip' => $_SERVER['REMOTE_ADDR'],
	 'customer_info' => $_SERVER['HTTP_USER_AGENT'],
	 'customer_login' => md5($_SERVER['REQUEST_TIME']),
	 'customer_lastonline' => date('Y-m-d H:i:s'));
	db::getInstance()->where('customer_name', $user);

	if (db::getInstance()->update('customer', $data))
	{
		// Set Session variable
		$_SESSION['activex'] = true;
		$_SESSION['customernamex'] = $user;
		$_SESSION['loginx'] = md5($_SERVER['REQUEST_TIME']);
		return true;
	}
	else
	{
		return false;
	}
}

/**
 * Check user and regenerate Session
 *
 * @return mixed returns true if the update ok
 */
function checkUser()
{ // Clear old Session and transfer Sessiondata in new Session
	session_regenerate_id(true);
	if (isset($_SESSION['activex']) and $_SESSION['activex'] !== true)
		return false;

	// Read Userdata from DB
	$result = db::getInstance()->rawQuery("SELECT customer_ip, customer_info, customer_login, " .
		"UNIX_TIMESTAMP(customer_lastonline) as customer_lastonline " .
		"FROM customer WHERE customer_name = '" .
		mysql_real_escape_string($_SESSION['customernamex']) .
		"' AND customer_active = '1'");

	if (db::getInstance()->count >= 1)
	{ // Check Data from DB and compare with the user data
		if (($result[0]['customer_ip'] != $_SERVER['REMOTE_ADDR']) or
			($result[0]['customer_info'] != $_SERVER['HTTP_USER_AGENT']) or
			($result[0]['customer_login'] != $_SESSION['loginx']) or
			(($result[0]['customer_lastonline'] + CUSTOMER_SESSION_TIME) <= $_SERVER['REQUEST_TIME']))
		{ 
			resetUser();
			return false;
		}
	}
	else
	{ 
		return false;
	}
	// If Userdata ok update last activity
	$data = Array('customer_lastonline' => date('Y-m-d H:i:s'));
	db::getInstance()->where('customer_name', $_SESSION['customernamex']);

	if (db::getInstance()->update('customer', $data))
		return true;
}

/**
 * Destroy session for Logout
 *
 * @param  none
 * @return none
 */
function resetUser()
{
	session_destroy();
	$_SESSION['activex'] = false;
	$_SESSION['customernamex'] = '';
	if (isset($_SESSION['ordererIdx']))
	{
		db::getInstance()->where('orderer_id', $_SESSION['ordererIdx']);
		db::getInstance()->delete('orderer');
		unset($_SESSION['ordererIdx']);
	}
	header('location: ' . URL);
	exit;
}

?>